﻿using AutoMapper;
using Domain.User;
using Infratructure.Interface;
using MD5Hash;
using MediatR;
using MES.Server.API.Application.Command.Account;
using ReturnValue;
using System.Transactions;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Account
{
    public class AccountAddHandler:IRequestHandler<AccountAddCommand,ApiResult<int>>
    {
        private readonly IRepository<AccountModel> accountway;
        private readonly IRepository<AccountRoleModel> accountroleway;
        private readonly IRepository<RoleModel> roleway;
        private readonly ILogger<LoginHandler> log;
        private readonly IRepository<DepartmeRoleModel> departmeroleway;
        private readonly IRepository<DepartmentModel> departmentway;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;

        public AccountAddHandler(IRepository<AccountModel> accountway, IRepository<AccountRoleModel>
            accountroleway, IRepository<RoleModel> roleway, ILogger<LoginHandler> log, IRepository<DepartmeRoleModel> departmeroleway,IRepository<DepartmentModel> departmentway,  IMapper mapper, IConfiguration configuration )
        {
            this.accountway = accountway;
            this.accountroleway = accountroleway;
            this.roleway = roleway;
            this.log = log;
            this.departmeroleway = departmeroleway;
            this.departmentway = departmentway;
            this.mapper = mapper;
            this.configuration = configuration;
        }
        /// <summary>
        /// 客户添加
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        public async Task<ApiResult<int>> Handle(AccountAddCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            try
            {
                var i = 0;
                var l = 0;
                var k = 0;
                var Count = accountway.GetAll().FirstOrDefault(x => x.AccountName == request.AccountName);
                if(Count!=null)  //账号查重
                {
                    res.Message = $"{DateTime.Now}:已有{request.AccountName},请不要重复添加";
                    res.Code = StatusCode.Fail;
                    return res;  //返回
                }
                var account = mapper.Map<AccountModel>(request);  
                account.Id = YitIdHelper.NextId();  //雪花
                account.AccountPwd = request.AccountPwd.GetMD5();  //密码
                AccountRoleModel ar = new AccountRoleModel()  //账号角色中间表数据配置
                {
                    Id = YitIdHelper.NextId(),
                    AccountId = account.Id,
                    RoleId = request.RoleId
                };
                DepartmeRoleModel dr = new DepartmeRoleModel()  //部门角色中间表配置
                {
                    Id = YitIdHelper.NextId(),
                    DepartmentId = request.DepartmentId,
                    RoleId = request.RoleId                    
                };
                var deparmentname = departmentway.GetAll().FirstOrDefault(x => x.Id==request.DepartmentId).DepartmentName; //部门名称
                var rolename = roleway.GetAll().FirstOrDefault(x => x.Id == request.RoleId).RoleName; //角色名称
                using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))  //允许异步的事务
                {
                    i = await accountway.AddAsync(account);
                    l = await accountroleway.AddAsync(ar);
                    k = await departmeroleway.AddAsync(dr);
                    tran.Complete();        //提交 否则回滚                                      
                }

                if (i > 0 && l > 0&&k>0)
                {
                    log.LogInformation($"{DateTime.Now}角色:{rolename},部门:{deparmentname},用户名:{request.AccountName}添加成功");
                    res.Data = i + l+k;
                    res.Message = $"{DateTime.Now}角色:{rolename},部门:{deparmentname},用户名:{request.AccountName}添加成功";
                    res.Code = StatusCode.Success;
                    return res;  //返回
                }
                else
                {

                    res.Message = $"{DateTime.Now}用户名:{request.AccountName}添加失败";
                    res.Code = StatusCode.Fail;
                    return res;  //返回
                }  
            }
            catch (Exception ex)
            {
                log.LogError($"{DateTime.Now}添加用户{request.AccountName}发生异常:{ex.Message}");
                throw;
            }
        }
    }
}
